package com.abu.listener;

import com.abu.utils.GeneratorCodeUtils;
import com.abu.utils.SmsTemplate;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class SmsListener {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SmsTemplate smsTemplate;

    private static final String PREFIX = "MEMBER.REGISTER.";
    private static final String EXCHANGE = "UCENTER.REGISTER";
    private static final String ROUTING = "UCENTER.REGISTER";
    private static final String QUEUE = "QUEUE.REGISTER";


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = QUEUE, durable = "true"),
            exchange = @Exchange(value = EXCHANGE, ignoreDeclarationExceptions = "true", type = ExchangeTypes.TOPIC),
            key = {ROUTING}
    ))
    public void receive(String phone) {
//        1.生成短信验证码
        int size = 6;
        String getCode = GeneratorCodeUtils.getCode(size);
//        2.发送验证码到手机
        try {
            smsTemplate.sendSms(phone, getCode);
        } catch (ClientException e) {
            e.printStackTrace();
        }
//        3.发送验证到缓存中,5分钟有效
        this.redisTemplate.opsForValue().set(PREFIX + phone, getCode, 5, TimeUnit.MINUTES);

    }
}
